package com.yq.dataStructures.tree;

import java.util.Arrays;

/**
 * @ClassName HeapSort
 * @Description 堆排序
 * @Author yaoqiang
 * @Date 2021/11/16 14:05
 * @Version 1.0
 */
public class HeapSort {
    public static void main(String[] args) {
        int[] arr = {4, 6, 8, 5, 9};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    private static void heapSort(int[] arr) {
        int temp = 0;
        for (int i = arr.length / 2 - 1; i >= 0; i--) {
            adJustBigHeap(arr, i, arr.length);
            //  adjuestSmallHeap(arr, i, arr.length);
        }
        for (int j = arr.length - 1; j > 0; j--) {
            temp = arr[j];
            arr[j] = arr[0];
            arr[0] = temp;
            adJustBigHeap(arr, 0, j);
            //adjuestSmallHeap(arr, 0, j);
        }
    }

    /**
     * 将以i对应的非叶子节点的树调整为大顶堆
     *
     * @param arr
     * @param i
     * @param length
     */
    private static void adJustBigHeap(int[] arr, int i, int length) {
        int temp = arr[i];
        for (int k = i * 2 + 1; k < length; k = k * 2 + 1) {
            //如果右节点存在，并且左比右小,k指向右节点
            if (k + 1 < length && arr[k] < arr[k + 1]) {
                k++;
            }
            if (arr[k] > temp) {
                //吧较大的赋值给当前节点，i也指向k继续循环比较
                arr[i] = arr[k];
                i = k;
            } else {
                break;
            }
        }
        arr[i] = temp;
    }

    private static void adjuestSmallHeap(int[] arr, int i, int length) {
        int temp = arr[i];
        for (int k = 2 * i + 1; k < length; k = 2 * k + 1) {
            if (k + 1 < length && arr[k] > arr[k + 1]) {
                k++;
            }
            if (arr[i] > arr[k]) {
                arr[i] = arr[k];
                i = k;
            } else {
                break;
            }
        }
        arr[i] = temp;
    }


}
